package com.zl.learning.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class TestXML {
    public static void main(String args[]) {
/**
 * string转xml
 */

        String sb = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<personList>" +
                "<name>onePerson</name>" +
                "<age>25</age>" +
                "<name>twoPerson</name>" +
                "<age>26</age>" +
                "<name>threePerson</name>" +
                "<age>27</age>" +
                "</personList>";
        Document doc = stringConvertXML(sb, "");
//从xml中解析name数据
        NodeList nl = doc.getElementsByTagName("name");//根据标签获得列表
        Node classNode = nl.item(0);//取列表中第一个对象
        String cName = classNode.getTextContent();//获取对象的值
        System.out.println(cName);
        classNode.setTextContent("ddddddddddd");//修改xml中对象的值
//从xml中解析age数据
        NodeList n2 = doc.getElementsByTagName("age");

        Node classNode2 = n2.item(2);
        System.out.println(classNode2.getTextContent());
        /**
         * xml转string
         */
        String strDoc = xmlConvertString(doc);
        System.out.println(strDoc);
    }

    /**
     * xml转字符串
     */
    public static String xmlConvertString(Document doc) {
        String xmlStr = null;
        try {
// XML转字符串
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.setOutputProperty("encoding", "utf-8");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            t.transform(new DOMSource(doc), new StreamResult(bos));
            xmlStr = bos.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlStr;
    }

    /**
     * string转xml
     */
    public static Document stringConvertXML(String data, String code) {
        StringBuilder sXML = new StringBuilder(code);
        sXML.append(data);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            InputStream is = new ByteArrayInputStream(sXML.toString().getBytes(StandardCharsets.UTF_8));
            doc = dbf.newDocumentBuilder().parse(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }
}